package com.zimu.h.hexowriter.config;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class HexoExecutor {

    public static int executeHexoCommand() throws IOException,InterruptedException {
        try {
            // 指定 Git Bash 的路径，根据实际情况在application.yml修改
            String gitBashPath = HexoWriterConfig.GIT_BASH_PATH;
            // 指定 Hexo 项目的根目录，根据实际情况在application.yml修改
            String hexoProjectPath = HexoWriterConfig.HEXO_ROOT_DIR;
            // 要执行的命令
            String command = "hexo clean && hexo g -d";

            // 创建 ProcessBuilder 对象
            ProcessBuilder processBuilder = new ProcessBuilder(gitBashPath, "-c", command);
            // 设置工作目录为 Hexo 项目的根目录
            processBuilder.directory(new File(hexoProjectPath));

            // 启动进程
            Process process = processBuilder.start();

            // 获取命令执行的输出结果
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 等待命令执行完成并获取返回值
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                System.out.println("命令执行成功");
                return exitCode;
            } else {
                System.out.println("命令执行失败，返回码: " + exitCode);
                return exitCode;
            }

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException("命令执行错误: " + e.getMessage() );
        }
    }
}